package org.alexdalton.jira;

import java.util.ArrayList;

import org.alexdalton.jira.JiraConn.LoginListener;
import org.alexdalton.jira.model.JiraServer;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ServerList extends OJActivity implements OnItemClickListener {
    ListView lst;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.serverlist);
        lst = (ListView) findViewById(R.id.serverList);
        loadServers();
        lst.setOnItemClickListener(this);
    }

    public void addServerDialog() {
        final AlertDialog addServer = new AlertDialog.Builder(this).create();

        LinearLayout mainl = new LinearLayout(this);
        mainl.setOrientation(LinearLayout.VERTICAL);
        mainl.setPadding(3, 3, 3, 3);

        TextView tv;
        final EditText serverName;
        final EditText serverUrl;
        final EditText login;
        final EditText password;

        tv = new TextView(this);
        tv.setText("Server Name");
        tv.setTextColor(0xffffffff);
        tv.setTypeface(Typeface.DEFAULT_BOLD);
        mainl.addView(tv);
        serverName = new EditText(this);
        mainl.addView(serverName);

        tv = new TextView(this);
        tv.setText("Server url");
        tv.setTextColor(0xffffffff);
        tv.setTypeface(Typeface.DEFAULT_BOLD);
        mainl.addView(tv);
        serverUrl = new EditText(this);
        mainl.addView(serverUrl);

        tv = new TextView(this);
        tv.setText("Login");
        tv.setTextColor(0xffffffff);
        tv.setTypeface(Typeface.DEFAULT_BOLD);
        mainl.addView(tv);
        login = new EditText(this);
        mainl.addView(login);

        tv = new TextView(this);
        tv.setText("Password");
        tv.setTextColor(0xffffffff);
        tv.setTypeface(Typeface.DEFAULT_BOLD);
        mainl.addView(tv);
        password = new EditText(this);
        mainl.addView(password);

        addServer.setButton("Save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                final String name = serverName.getText().toString();
                final String url = serverUrl.getText().toString();
                final String user = login.getText().toString();
                final String pass = password.getText().toString();
                final JiraConn conn = new JiraConn(url, user, pass);
                final ProgressDialog dlg = new ProgressDialog(ServerList.this);
                dlg.setMessage("Testing connection");
                dlg.show();
                conn.setOnLoginListener(new LoginListener() {
                    public void onLoginError(final Exception e) {
                        dlg.dismiss();
                        ServerList.this.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(ServerList.this, "Error connecting server " + e, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                    
                    public void onLoginComplete() {
                        dlg.dismiss();
                        addServer.dismiss();
                        ServerList.this.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(ServerList.this, "Connection successfull ", Toast.LENGTH_LONG).show();
                                JiraApp.get().addServer(name, url, user, pass);
                                loadServers();
                            }
                        });
                    }

                    public void onSyncProgress(String message, int progress, int max) {
                        // TODO Auto-generated method stub

                    }
                });
                conn.testLogin();
            }
        });
        addServer.setView(mainl);
        addServer.setTitle("Add Server");
        addServer.show();
    }

    ArrayList<JiraServer> servers;

    public void loadServers() {
        servers = JiraApp.get().getServerList();
        String[] labels = new String[servers.size()];
        for (int i = 0; i < servers.size(); i++) {
            labels[i] = servers.get(i).getName();
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, R.id.text, labels);
        lst.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_NEW, 1, "Add Server").setIcon(android.R.drawable.ic_menu_add);
        menu.add(0, MENU_PREFERENCES, 2, R.string.preferences).setIcon(android.R.drawable.ic_menu_preferences);

        return super.onCreateOptionsMenu(menu);
    }

    private static final int MENU_NEW = 101;
    private static final int MENU_PREFERENCES = 102;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean handled = false;
        switch (item.getItemId()) {
            case MENU_NEW:
                addServerDialog();
                handled = true;
                break;
            case MENU_PREFERENCES:
                startActivity(new Intent(this, JiraPreferences.class));
                handled = true;
                break;
        }
        return handled;
    }

    public void onItemClick(AdapterView< ? > arg0, View arg1, int arg2, long arg3) {
        Intent i = new Intent(this, JiraFilters.class);
        i.setData(Uri.parse("jira://showFilters?server=" + servers.get(arg2).getName()));
        startActivity(i);
    }

}
